<?php

namespace App\Http\Controllers\Api;

use App\Model\MachineSlots;
use App\Model\SalesDetail;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\DB;

class IndexController extends BaseController
{
    //出货通知接口
    public function chuhuo(Request $request){
        try{
            $arr_midParams = $request->get('arr_xmlData');//中间件产生的参数
            //插入销售记录
            DB::enableQueryLog();
            $model_slotsInfo = MachineSlots::where([
                'machine.machine_id'=>trim($arr_midParams['sb_id']),
                'machine_slots.slot_id'=>$arr_midParams['huodao'],
            ])
                ->join('machine', 'machine.id', '=', 'machine_slots.machine_id')
                ->select([
                    'machine.cost as machine_cost',
                    'machine_slots.good_cost as good_cost',
                    'machine_slots.id as id',
                    'machine_slots.good_id as good_id',
                    'machine_slots.good_name as good_name',
                    'machine_slots.surplus as surplus',
                ])
                ->first();
            $float_profit =  $arr_midParams['amount'] - ($arr_midParams['amount']*$model_slotsInfo->machine_cost) - $model_slotsInfo->good_cost;
            try{
                DB::beginTransaction();
                $model_slotsInfo->surplus--;//货道已有数量-1
                $model_slotsInfo->save();
                SalesDetail::insert([
                    'machine_id'=> $arr_midParams['sb_id'],
                    'goods_id'=> $model_slotsInfo->good_id,
                    'goods_name'=> $model_slotsInfo->good_name,
                    'goods_cost'=> $model_slotsInfo->good_cost,
                    'sale_price'=> $arr_midParams['amount'],
                    'sale_time'=> strtotime($arr_midParams['create_time']),
                    'slots_id'=>$arr_midParams['huodao'],
                    'profit'=>$float_profit,
                ]);
                DB::commit();
                return view('api/chuhuo',[
                    'return_code'=>'SUCCESS',
                    'return_msg'=>'OK',
                ]);
            }
            catch (\Exception $exception){
                echo $exception->getMessage();exit;
                DB::rollBack();
            }

        }catch (\Exception $exception){
            return view('api/chuhuo',[
                'return_code'=>'ERROR',
                'return_msg'=>'ERROR',
            ]);
        }
    }

}
